package com.ehotting.edsta.circuitDesign.gen.circuit.helper;

import com.ehotting.edsta.circuitDesign.domain.EsCircuit;
import com.ehotting.edsta.circuitDesign.domain.EsRuleScript;
import com.ehotting.edsta.circuitDesign.gen.ScriptConstants;
import com.ehotting.edsta.circuitDesign.gen.ScriptLogger;
import com.ehotting.edsta.circuitDesign.gen.element.helper.ElementScriptHelper;
import com.ehotting.eaf.core.utils.StringUtils;
import org.codehaus.groovy.tools.StringHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
public class CircuitScriptHelper {



    public String genMainMethod(EsCircuit circuit, String methodBody, String callBody, List<String> argumentList ){
        StringBuffer buf = new StringBuffer();
        buf.append(ScriptConstants.defineImport());

        buf.append(methodBody);
        buf.append(ScriptConstants.LINE);
        buf.append("def ");
        buf.append(genMethodNameAndArgument(genMainName(circuit.getId()),argumentList));
        buf.append( "{");
        if(StringUtils.hasText(callBody)){
            buf.append(ScriptConstants.LINE);
            buf.append(callBody);
        }
        buf.append(ScriptConstants.LINE);
        buf.append(ScriptConstants.TAB);
        if(StringUtils.hasText(callBody)) {
            buf.append("return true;");
        }else{
            buf.append("return false;");
        }
        buf.append(ScriptConstants.LINE);
        buf.append("};");
        String script = buf.toString();

        ScriptLogger.info(script);

        return script;
    }

    public String genMethodNameAndArgument(String methodName,List<String> inputParamList){
        StringBuffer buf = new StringBuffer();
        buf.append(methodName).append("(");
        for (String argName : inputParamList){
            buf.append(argName).append(",");
        }
        buf.append("ctx,all");
        buf.append( ")");

        return buf.toString();
    }


    public String genMethodName(EsRuleScript esRuleScript){
        return "cir_"+esRuleScript.getType().toString().toLowerCase() + "_"+esRuleScript.getId();
    }


    public String genVar(EsRuleScript esRuleScript){
        return "var_"+esRuleScript.getType().toString().toLowerCase() + "_"+esRuleScript.getId();
    }

    public String genMainName(Long circuitId){
        return "main_circuit_"+circuitId;
    }

}